/**
 * 功能：本文件主要实现了nodejs版本的$.ajax方法，使用基本和jQuery.ajax相同
 * 朱冯博
 */

var request = require("request").defaults({
    pool: { maxSockets: 5000 }
});
var querystring= require('querystring');
function ajax(options) {
    options.method = options.type;
    options.json = true;
    options.timeout = 120000;
    if(options.type.toLowerCase() == "get") {
        options.data = querystring.stringify(options.data);
        //options.headers["content-length"] = Buffer.byteLength(JSON.stringify(options.data), 'utf-8');
        if(options.url.indexOf("?") > -1) {
            options.url += "&" + options.data;
        } else {
            options.url += "?" + options.data;
        }
    } else {
        options.body = options.data;
        //options.headers["content-length"] = Buffer.byteLength(JSON.stringify(options.data), 'utf-8');
    }
    delete options.data;
    request(options, function(error, response, body) {
        if(!error && body) {
            options.success(body, response);
        } else {
            options.success({"errorCode": "-1", errorMsg:"服务器接口错误", data:null});
        }
    });
}
exports.ajax = ajax;